package com.cinema;

import java.io.IOException;

import javax.jdo.JDOHelper;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.cinema.data.FilmInfo;
import com.cinema.data.Ticket;
import com.cinema.data.User;

import query.DataQuery;

public class Booking extends HttpServlet{
	
	public Booking(){
		super();
	}
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doPost(req, resp);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		long id = Long.parseLong(request.getParameter("id"));
		DataQuery query = new DataQuery();
		FilmInfo film = query.getFilm(id);
		System.out.println("Booking.java" + JDOHelper.getPersistenceManager(film));
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("user");
		if(user == null){
			response.sendRedirect("index.jsp");
		}else{
			FilmInfo f = (FilmInfo)session.getAttribute("film");
			Ticket t = (Ticket)session.getAttribute("ticket");
			
			if(f != null)
				session.removeAttribute("film");
			if(t != null)
				session.removeAttribute("ticket");
			
			if(film != null){
				t = new Ticket();
				t.setUsrid(user.getuID());
				t.setFilmid(id);
				session.setAttribute("film", film);
				session.setAttribute("ticket", t);
				String url = "/booking1.jsp";
				RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher(url);
				try {
					dispatcher.forward(request, response);
				} catch (ServletException e) {
					e.printStackTrace();
				}
			}else{
				response.sendRedirect("index.jsp");
			}
		}
	}
}
